import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  PurchaseOrdersGetOrderNumber,
  GetProductCategoriesName,
  ProcurementCooperationUpdateSignStatus,
  PurchaseOrdersGetAllByPagedAndSort,
  GetSignedSupplierEnterpriseInfoNames,
  PurchaseOrdersCreate,
  GetDictionaryByDictCode,
  PurchaseOrdersGetInfoById,
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted, computed } from "vue";
import qs from "qs";
import { FXQ } from "@/utils/public/FXQ"
export function useEBusinessPurchase() {
  const route = useRoute()
  const Visible = ref(false)
  const loading = ref<boolean>(false);
  const dataList = ref<any>([]);
  const Visible_formList = ref();
  const showList = ref()
  const showFormList = ref()
  const showVisible = ref<boolean>(false);
  const RefStubimAddFrom = ref();
  const isSeal = ref<boolean>(false)
  const regex = /^[\u4e00-\u9fa5a-zA-Z0-9]*$/ //校验字符汉汉字
  const duplicateRegex = /(\S).*\1/ //校验是否重复
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const stubim_form = reactive({
    defaultInfo: '***',
    orderNumber: "",
    orderDate: "",
    purchaserInformation: "xxxx电商企业公司",
    seiId: '',
    status: 0,
    purchaseDetails: '',
    purchaseName: '',
    deliveryDate: '',
    modeOfDelivery: '货交承运人',
    deliveryAddress: '******',
    invoiceType: '增值税专用发票',
    taxRate: '13%',
    paymentMethod: '在线支付',
    paymentAgreement: '',
    otherAgreement: '',
    totalMoney: '',
  })

  const supplierList = ref()
  const payList = ref()
  const rules: any = {
    seiId: [
      {
        required: true,
        message: '请选择供应商',
        trigger: 'blur',
      }
    ],
    deliveryDate: [
      {
        required: true,
        message: '请选择交货日期',
        trigger: 'blur',
      }
    ],
    purchaseName: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!regex.test(value)) {
            return callback(new Error('不得输入特殊字符'))
          } else if (!value) {
            return callback(new Error('请输入采购名称'))
          }
          else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    paymentAgreement: [
      {
        required: true,
        message: '请选择付款约定',
        trigger: 'blur',
      }
    ],
  };
  const columns = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "采购项目名称",
      prop: "purchaseName",
    },
    {
      label: "供应商企业名称",
      prop: "supplyName",
    }, {
      label: "采购订单号",
      prop: "orderNumber",
    },
    {
      label: "订购日期",
      prop: "orderDate",
    }, {
      label: "交货日期",
      prop: "deliveryDate",
    },
    {
      label: "交货地址",
      prop: "deliveryAddress",
    },
    {
      label: "订单状态",
      prop: "status",
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.status == "0" ? "warning" :
            row.status == "1" ? "success" :
              "danger"}>
          {
            row.status == "0" ? "未处理" :
              row.status == "1" ? "已接受" :
                "已拒绝"
          }
        </el-tag>
      )
    }, {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

  // 签订
  async function ConcludeSign(row) {
    const data = qs.stringify({
      id: row.procurementCooperationId
    })
    const res = await ProcurementCooperationUpdateSignStatus(data)
    if (res.success) {
      ElMessage.success(res.msg);
      getClientBaseData()
    } else {
      ElMessage.error(res.msg)
    }
  }
  async function GetContractNumber(date) {
    let data = qs.stringify({
      selectedDate: date,
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    const res = await PurchaseOrdersGetOrderNumber(data);
    if (res.success) {
      stubim_form.orderNumber = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }

  function changeDate() {
    const date1 = new Date(stubim_form.orderDate);
    const date2 = new Date(stubim_form.deliveryDate);
    if (date1 >= date2) {
      ElMessage.warning("交货日期不得早于订购日期")
      stubim_form.deliveryDate = ''
    }
    if (stubim_form.orderDate !== null) {
      GetContractNumber(stubim_form.orderDate)
    }
  }
  async function getNameAndNum_() {
    const data1 = {
      taskId: route.query.taskId,
      planId: route.query.planId
    }
    const res2 = await GetSignedSupplierEnterpriseInfoNames(data1)
    const res3 = await GetProductCategoriesName()
    let data = qs.stringify({
      dictCode: 'DuePaymentDate'
    })
    const res4 = await GetDictionaryByDictCode(data)
    if (res2.success) {
      supplierList.value = res2?.data;
    } else {
      ElMessage.success(res2.msg)
    }
    if (res3.success) {
      Visible_formList.value = res3.data;
    } else {
      ElMessage.error(res3.msg)
    }
    if (res4.success) {
      payList.value = res4.data;
    } else {
      ElMessage.success(res4.msg)
    }
  }
  //多次新增需要刷新订单编号
  async function addOrder() {
    Visible.value = true
  }

  // 分页获取订单列表
  async function getClientBaseData() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      SEIId: '',
    }
    const res = await PurchaseOrdersGetAllByPagedAndSort(data);
    if (res.success) {
      res.data.items.forEach(item => {
        item.orderDate = item.orderDate.substring(0, 10)
        item.deliveryDate = item.deliveryDate.substring(0, 10)
      })
      dataList.value = res.data.items;
      pagination.total = res.data.totalCount
    } else {
      ElMessage.error(res.msg)
    }
  }

  //输入个数计算总数
  function changeNumber(item) {
    item.number = validatedNumber(item.number)
    if (!item.number) {
      item.total = '0.00'
      return
    } else {
      item.total = (item.number * item.money).toFixed(2)
      stubim_form.totalMoney = Visible_formList.value.reduce((sum, item) => {
        if (item.total) {
          return sum + parseFloat(item.total);
        }
        return sum;
      }, 0);
    }
  }

  async function SubtimPurchase(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      if (stubim_form.orderDate == "" || stubim_form.orderDate == null) {
        ElMessage.warning("未选择订购日期")
        return
      }
      const hasGreaterThanOne = Visible_formList.value.some(item => item.number && parseInt(item.number) >= 1);
      if (!hasGreaterThanOne) {
        ElMessage.warning("请至少订购一种商品")
        return
      }
      if (!isSeal.value) {
        ElMessage.warning("电商企业未盖章")
        return
      }
      if (stubim_form.paymentAgreement == '') {
        ElMessage.warning("请选择付款约定")
        return
      }
      const data = {
        orderNumber: stubim_form.orderNumber,
        orderDate: stubim_form.orderDate,
        purchaserInformation: stubim_form.purchaserInformation,
        seiId: stubim_form.seiId,
        status: 0,
        purchaseName: stubim_form.purchaseName,
        modeOfDelivery: stubim_form.modeOfDelivery,
        deliveryAddress: stubim_form.deliveryAddress,
        invoiceType: stubim_form.invoiceType,
        taxRate: stubim_form.taxRate,
        paymentMethod: stubim_form.paymentMethod,
        deliveryDate: stubim_form.deliveryDate,
        paymentAgreement: stubim_form.paymentAgreement,
        otherAgreement: stubim_form.otherAgreement,
        planId: route.query.planId,
        taskId: route.query.taskId,
        PurchaseDetails: []
      }
      Visible_formList.value.forEach(item => {
        data.PurchaseDetails.push({
          ProductName: item.categoryName,
          Specifications: item.Specifications || '',
          Quantity: Number(item.number) || 0,
          Price: item.money,
          ProductId: item.productId
        })
      })
      data.PurchaseDetails = JSON.stringify(data.PurchaseDetails)
      let res = await PurchaseOrdersCreate(data)
      if (res.success) {
        ElMessage.success(res.msg);
        getClientBaseData()
        ClosePurchase()
      } else {
        ElMessage.error(res.msg);
      }
    })
  }
  // 盖章
  function Signet() {
    // // 生成章
    const MYFXQ = FXQ.companySeal('xxxx电商企业公司', 0, 0, '', '');
    let view_FQX = document.querySelector("#view_FQX");
    let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
    view_FQX.innerHTML = MYFQX;
    isSeal.value = true
  }
  //校验比较时间
  function changeDeliveryDate() {
    if (!stubim_form.orderDate) {
      ElMessage.warning("请先选择订购日期")
      stubim_form.deliveryDate = ''
      return
    }
    const date1 = new Date(stubim_form.orderDate);
    const date2 = new Date(stubim_form.deliveryDate);
    if (date1 >= date2) {
      ElMessage.warning("交货日期不得早于订购日期")
      stubim_form.deliveryDate = ''
    }
  }
  function ClosePurchase() {
    stubim_form.orderDate = ''
    stubim_form.deliveryDate = ''
    stubim_form.purchaseName = ''
    stubim_form.modeOfDelivery = '货交承运人'
    stubim_form.deliveryAddress = '******'
    stubim_form.seiId = ''
    stubim_form.invoiceType = '增值税专用发票'
    stubim_form.taxRate = '13%'
    stubim_form.paymentMethod = '在线支付'
    stubim_form.paymentAgreement = ''
    stubim_form.totalMoney = ''
    Visible.value = false
    Visible_formList.value.forEach(item => {
      item.categoryName = item.categoryName
      item.money = item.money
      item.number = '',
        item.productId = item.productId,
        item.total = ''
    })
    isSeal.value = false
  }
  onMounted(() => {
    getClientBaseData()
    getNameAndNum_()
  })
  function handleSizeChange() {
    getClientBaseData()
  }
  function handleCurrentChange() {
    getClientBaseData()
  }

  async function handleOrder(row) {
    const data = qs.stringify({
      id: row.purchaseOrderId
    })
    let res = await PurchaseOrdersGetInfoById(data)
    if (res.success) {
      showFormList.value = res?.data
      showFormList.value['defaultInfo'] = '****'
      showList.value = JSON.parse(res?.data.purchaseDetails)
      let total = 0
      //计算商品总额
      showList.value.forEach(item => {
        item.total = item.Price * item.Quantity
        total = total + (item.total)
      })
      showFormList.value['totalMoney'] = total
      showVisible.value = true
      nextTick(() => {
        const MYFXQ = FXQ.companySeal('xxxx电商企业公司', 0, 0, '', '');
        let view_FQX = document.querySelector("#view_SHOWFQX");
        let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
        view_FQX.innerHTML = MYFQX;
        if (row.status == 1) {
          const supplierName = supplierList.value.filter(item => item.seiId == showFormList.value['seiId'])[0]?.supplyName
          const MYFXQ = FXQ.companySeal(supplierName, 0, 0, '', '');
          let view_FQX = document.querySelector("#view_SHOWFQX1");
          let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
          view_FQX.innerHTML = MYFQX;
          isSeal.value = true
        }
      })
    } else {
      ElMessage.error(res.msg);
    }
    //渲染采购方印章
  }

  function validatedNumber(row) {
    console.log(Number(row));
    if (Number(row) > 10000) {
      return 10000
    }
    if (Number(row) < 0) {
      console.log('进来了负数');

      return 0
    }
    if (!Number.isInteger(Number(row))) {
      return Math.floor(Number(row))
    }
    return row
  }

  return {
    Visible,
    columns,
    loading,
    dataList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    stubim_form,
    Visible_formList,
    ConcludeSign,
    changeNumber,
    payList,
    supplierList,
    rules,
    RefStubimAddFrom,
    SubtimPurchase,
    ClosePurchase,
    changeDeliveryDate,
    Signet,
    isSeal,
    addOrder,
    showList,
    showFormList,
    showVisible,
    handleOrder,
    changeDate,
    validatedNumber
  }
}
